package com.ayh.campusfun.controller.api.v1;

import cn.hutool.core.bean.BeanUtil;
import com.ayh.campusfun.common.CommonResult;
import com.ayh.campusfun.common.core.jwt.JWTUtils;
import com.ayh.campusfun.common.exception.http.ForbiddenException;
import com.ayh.campusfun.entity.FunComment;
import com.ayh.campusfun.entity.Users;
import com.ayh.campusfun.service.FunCommentService;
import com.ayh.campusfun.service.FunShareService;
import com.ayh.campusfun.vo.AddCommentVO;
import com.ayh.campusfun.vo.CommentVO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 趣事评论表(FunComment)表控制层
 *
 * @author ayh
 * @since 2021-03-20 20:42:37
 */
@RestController
@RequestMapping("funComment")
public class FunCommentController {
    /**
     * 服务对象
     */
    @Autowired
    private FunCommentService funCommentService;

    @Autowired
    private FunShareService funShareService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Resource
    private JWTUtils jwtUtils;

    @PostMapping(value = "/findCommentList",produces = "application/json")
    public CommonResult getCommentList(Long funId){
        Map<String,Object> map = new HashMap<>();
        map.put("funId",funId);
        return CommonResult.success(CommentVO.buildFunCommentList(funCommentService.findListByParam(map)));
    }

    @PostMapping(value = "/addComment",produces = "application/json")
    public CommonResult addComment(HttpServletRequest request,FunComment funComment){
        String authorization = jwtUtils.getTokenFromRequest(request);
        Users users = (Users) redisTemplate.opsForValue().get(authorization);
        if(users==null){
            throw new ForbiddenException(60009);
        }
        funComment.setUid(users.getUid());
        funComment.setAvatarUrl(users.getAvatarUrl());
        funComment.setNickName(users.getNickName());
        funCommentService.insert(funComment);
//        funShareService.commentById(funComment.getFunId());
        funShareService.commentById(funComment.getFunId());
        FunComment funCommentById = funCommentService.findById(funComment.getId());
        AddCommentVO<FunComment> addCommentVO = new AddCommentVO<>();
        BeanUtil.copyProperties(funCommentById,addCommentVO);
        addCommentVO.setChildList(new ArrayList<>());
        return CommonResult.success(addCommentVO);
    }
}
